package com.sinopec.uhf.initrc

import com.sinopec.uhf.model.ReaderHelper
import com.payne.reader.base.Consumer
import com.payne.reader.bean.receive.Failure
import com.payne.reader.bean.receive.OperationTag
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch


internal object CoroutineRead {

    private var sBtAntNum = -1

    fun readATag(): Flow<OperationTag?> {
        return channelFlow<OperationTag?> {
            val config = Config.defaultConfig
            launch {
                while (currentCoroutineContext().isActive) {
                    changeWorkAntenna()
                    delay(config.changeWorkAntennaTime)
                }
            }

            delay(10)
            val consumer = Consumer<OperationTag?> {
                trySend(it)
            }
            val consumerFail = Consumer<Failure?> {
                /* no-op */
            }
            while (currentCoroutineContext().isActive) {
                readTagOneTime(consumer, consumerFail)
                delay(config.readTagOneTime)
            }

            awaitClose {

            }

        }
    }


    //读一次tag
    private fun readTagOneTime(
        consumer: Consumer<OperationTag?>?,
        consumerFail: Consumer<Failure?>?
    ) {
        val config = Config.defaultConfig
        ReaderHelper.getReader().readTag(config.readConfig, consumer, consumerFail)
    }

    private fun changeWorkAntenna() {
        if (sBtAntNum == 0) {
            sBtAntNum = 1
        } else if (sBtAntNum == 1) {
            sBtAntNum = 2
        } else if (sBtAntNum == 2) {
            sBtAntNum = 3
        } else if (sBtAntNum == 3) {
            sBtAntNum = 4
        } else if (sBtAntNum == 4) {
            sBtAntNum = 5
        } else {
            sBtAntNum = 0
        }
        ReaderHelper.getReader().setWorkAntenna(
            sBtAntNum,
            {
                //Log.e("123===", "天线切换成功：" + sBtAntNum);
            },
            {
                //String failureStr = StringFormat.format(failure.getCmd(), failure.getErrorCode());
                //Log.e("123===", failureStr + "   天线切换失败：" + sBtAntNum);
            })

    }

}